package com.example.administrator.exkotlin.endurance

import android.content.ContentValues
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import com.example.administrator.exkotlin.MyApplication
import com.example.administrator.exkotlin.R
import kotlinx.android.synthetic.main.activity_endurance.*
import java.io.*
import java.lang.Exception
import kotlin.text.StringBuilder

/**
 * 持久化例子
 * */
class EnduranceActivity : AppCompatActivity() {

    val path = "data"
    var version = 2

    lateinit var dbHelper: MyDatabaseHelper
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_endurance)
        dbHelper = MyDatabaseHelper(this, "BookStore.db", version++)
        initDatas()

        //自定义扩展函数来保存SharedPreferences数据
        MySharedPreferences.save {
            putBoolean("test", true)
            putString("testString", "成功")
            putFloat("testFloat", 19.9f)
            putInt("testInt", 20)
        }
    }

    //记载本地和SharedPreferences中的数据
    private fun loadLoaclAndShare() {
        val strings = StringBuilder().apply {
            append(readFileInLocal(path).toString())
            append(MySharedPreferences.read("test", true))
            append(MySharedPreferences.read("testString", ""))
            append(MySharedPreferences.read("testFloat", 10f))
            append(MySharedPreferences.read("testInt", 20))
            append(MySharedPreferences.read("testLong", 200L))
        }
        tv_read.text = strings.toString()
    }

    private fun initDatas() {
        loadLoaclAndShare()

        btn_save.setOnClickListener {
            saveFileToLocal(ed_input.text.toString(), path)
            ed_input.setText("")
        }

        btn_initdb.setOnClickListener {
            dbHelper.writableDatabase
        }

        btn_db_add.setOnClickListener {
            insertDb()
        }
        btn_db_update.setOnClickListener {
            updateDb()
        }
        btn_db_delete.setOnClickListener {
            deleteDb()
        }
        btn_db_query.setOnClickListener {
            queryDb()
        }

    }

    //添加数据
    private fun insertDb() {
        val db = dbHelper.writableDatabase
        //开启事务
        db.beginTransaction()
        try {
            val content1 = ContentValues().apply {
                put("name", "${System.currentTimeMillis()}")
                put("author", "lp")
                put("pages", 300)
                put("price", 99.99)
            }
            db.insert("Book", null, content1)
            queryDb()
            //操作完成
            db.setTransactionSuccessful()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            db.endTransaction()
        }

    }

    //更新数据
    private fun updateDb() {
        val db = dbHelper.writableDatabase
        val content = ContentValues()
        content.put("pages", 600)

        db.update("Book", content, "author = ?", arrayOf("lp"))
        queryDb()
    }

    //删除数据
    private fun deleteDb() {
        val db = dbHelper.writableDatabase
        //删除价格超过50 的数据,不指定则会删除所有
        db.delete("Book", "price > ?", arrayOf("99.1"))
        queryDb()
    }

    //查询数据
    private fun queryDb() {
        val db = dbHelper.writableDatabase
        val cursor = db.query("Book", null, null, null, null, null, null)
        if (cursor.moveToFirst()) {
            val stringBuilder = StringBuilder()
            do {
                stringBuilder.append("\r\n")
                stringBuilder.append("name is ${cursor.getString(cursor.getColumnIndex("name"))}")
                stringBuilder.append(" author is ${cursor.getString(cursor.getColumnIndex("author"))}")
                stringBuilder.append(" pages is ${cursor.getString(cursor.getColumnIndex("pages"))}")
                stringBuilder.append(" price is ${cursor.getString(cursor.getColumnIndex("price"))}")

            } while (cursor.moveToNext())

            tv_read.text = stringBuilder.toString()
        } else {
            tv_read.text = " "
        }
        cursor.close()
    }


    //保存数据到本地文件
    private fun saveFileToLocal(str: String, path: String) {
        if (TextUtils.isEmpty(str)) {
            return
        }
        //打开一个输出通道，将数据保存到指定文件中 MODE_PRIVATE替换， MODE_APPEND追加
        val output = openFileOutput(path, Context.MODE_PRIVATE)
        val bufferedWriter = BufferedWriter(OutputStreamWriter(output))
        //使用 use内置扩展函数，保证llambda表达式中的代码全部执行后自动关闭外层的流
        bufferedWriter.use {
            it.write(str)
        }

        tv_read.text = readFileInLocal(path).toString()
    }

    //从文件中读取数据
    private fun readFileInLocal(path: String): StringBuilder {
        var result = StringBuilder()
        try {
            val openFileInput = openFileInput(path)
            val bufferedReader = BufferedReader(InputStreamReader(openFileInput))
            bufferedReader.use {
                it.forEachLine {
                    result.append(it)
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return result
    }

}
